package com.example.dollarShipping.controller;


import com.example.dollarShipping.entity.TruckOrder;
import com.example.dollarShipping.service.DriverService;
import com.example.dollarShipping.utils.Result;
import com.example.dollarShipping.utils.ResultCode;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController()
@RequestMapping("/driver")
public class DriverController {

    @Resource
    DriverService driverService;

    ResultCode resultCode = new ResultCode();


    @GetMapping("/getTruckOrder")
    @PreAuthorize("hasAnyAuthority('admin','driver')")
    public Result getTruckOrder(@RequestParam Long id){
        Result res = new Result();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<TruckOrder> list = driverService.getTruckOrder(id);
            map.put("truckOrderList",list);
            res.setMessage("返回成功");
            res.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            res.setCode(resultCode.InfoGetERR);
            res.setMessage(resultCode.getMsg(resultCode.InfoGetERR));
        }
        return res;
    }

    // 货运单签收/结算操作
    // 修改货运单状态并添加任务记录
    @PostMapping("/driverOperate")
    @PreAuthorize("hasAnyAuthority('admin','driver')")
    public Result driverOperate(@Validated @RequestBody  Map<String,Object> params){
        Integer state = (Integer) params.get("state");//3-揽收，4发车,5-到达新位置,6-到达,7-上报意外情况
        Long id = Long.parseLong(params.get("id").toString());
        Long operator = Long.parseLong(params.get("operator").toString());
        String location ="";
        String unexpectedInfo ="";
        Double unexpectedPrice = 0.0;
        if(params.get("location")!=null)
            location  = (String) params.get("location");
        if(params.get("unexpectedInfo")!=null)
            unexpectedInfo = (String) params.get("unexpectedInfo");
        if(params.get("unexpectedPrice")!=null)
            unexpectedPrice = Double.parseDouble(params.get("unexpectedPrice").toString());
        Result res = new Result();
        try {
            String r = driverService.changeState(state, id, operator, location,unexpectedInfo,unexpectedPrice);
            res.setMessage(r);
        } catch (Exception e) {
            e.printStackTrace();
            res.setCode(ResultCode.OpERR);
            res.setMessage(resultCode.getMsg(ResultCode.OpERR));
        }
        return res;
    }


}
